<template>
  <div>
    <a-modal :title="title" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="1200px" :mask-closable="false">
      <a-scrollbar style="height: 600px; overflow: auto">
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-row>
            <a-col :span="6">
              <a-form-item field="platform" label="平台：" :rules="rules.platform">
                <a-select v-model="form.platform" allow-clear placeholder="请选择" allow-search :fallback-option="() => ''">
                  <a-option value="AMAZON" label="amazon"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="platformOrderNumber" label="平台订单号：" :rules="rules.platformOrderNumber">
                <a-input placeholder="请输入平台订单号" v-model="form.platformOrderNumber" />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="8">
              <a-form-item field="marketplaceId" label="站点：" :rules="rules.marketplaceId">
                <a-select v-model="form.marketplaceId" placeholder="请选择站点" @change="changeMarket" allow-clear allow-search>
                  <a-option v-for="item of marketList" :label="item.marketplaceName + '-' + item.marketplaceCode" :value="item.marketplaceId"></a-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :span="6">
              <a-form-item field="sellerMarketId" label="店铺：" :rules="rules.sellerMarketId">
                <a-select :trigger-props="{ autoFitPopupMinWidth: true }" v-model="form.sellerMarketId" placeholder="请选择站点" @change="changeShop" allow-clear allow-search>
                  <a-option v-for="item of userShopList" :label="item.shopName" :value="item.sellerMarketId"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="buyerName" label="买家名称：" :rules="rules.buyerName">
                <a-input placeholder="请输入买家名称" v-model="form.buyerName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="买家邮箱：">
                <a-input placeholder="请输入买家邮箱" v-model="form.buyerEmail" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="买家留言：">
                <a-input placeholder="请输入买家留言" v-model="form.buyerLeaveMessage" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="gmtPurchase" label="订购时间：" :rules="rules.gmtPurchase">
                <a-date-picker placeholder="请选择订购时间" v-model="form.gmtPurchase" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="gmtLatestShip" label="承诺发货时间：" :rules="rules.gmtLatestShip">
                <a-date-picker placeholder="请选择发货时间" v-model="form.gmtLatestShip" />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="8">
              <a-form-item label="订单备注：">
                <a-input placeholder="请输入订单备注" v-model="form.remark" />
              </a-form-item>
            </a-col> -->
            <a-col :span="6">
              <a-form-item field="userName" label="收货人：" :rules="rules.userName">
                <a-input placeholder="请输入收货人" v-model="form.userName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="phoneNumber" label="手机号：" :rules="rules.phoneNumber">
                <a-input placeholder="请输入手机号" v-model="form.phoneNumber" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="country" label="国家：" :rules="rules.country">
                <a-select :trigger-props="{ autoFitPopupMinWidth: true }" v-model="form.country" placeholder="请选择国家" @change="changeCountry" allow-clear allow-search>
                  <a-option v-for="item of countriesOptions" :label="item.name + '-' + item.short" :value="item.short"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="stateOrRegion" label="省/州：" :rules="rules.stateOrRegion">
                <a-input placeholder="请输入省/州" v-model="form.stateOrRegion" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="stateOrRegionCode" label="省/州代码：" :rules="rules.stateOrRegionCode">
                <a-input placeholder="请输入省/州代码" v-model="form.stateOrRegionCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="city" label="城市名称：" :rules="rules.city">
                <a-input placeholder="请输入城市名称" v-model="form.city" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="postalCode" label="邮编：" :rules="rules.postalCode">
                <a-input placeholder="请输入邮编" v-model="form.postalCode" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="address" label="地址1：" :rules="rules.address">
                <a-input placeholder="请输入地址1" v-model="form.address" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="地址2：">
                <a-input placeholder="请输入地址2" v-model="form.address1" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="地址3：">
                <a-input placeholder="请输入地址3" v-model="form.address2" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="发货仓：">
                <a-select :trigger-props="{ autoFitPopupMinWidth: true }" v-model="form.warehouseCode" placeholder="请选择发货仓" @change="changeWarehouse" allow-clear allow-search>
                  <a-option v-for="item of houseList" :label="item.warehouseName" :value="item.warehouseCode"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="物流商：">
                <a-select :trigger-props="{ autoFitPopupMinWidth: true }" v-model="form.expressId" placeholder="请选择物流商" @change="changeExpress" allow-clear allow-search>
                  <a-option v-for="item of expressList" :label="item.expressName" :value="item.id"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="物流渠道：">
                <a-select :trigger-props="{ autoFitPopupMinWidth: true }" v-model="form.expressChannelCode" placeholder="请选择物流渠道" @change="getChannelItem" allow-clear allow-search>
                  <a-option v-for="item of channelList" :label="item.name" :value="item.code"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注：">
                <a-input v-model="form.remark" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div>
          <a-button type="primary" @click="addProduct.visible = true">添加商品</a-button>
          <span style="margin: 0 10px">(已添加 {{ skuNum }} 种商品)</span>
          <span>币种：</span>
          <a-select placeholder="请选择币种" v-model="form.currency" style="width: 180px" allow-search allow-clear>
            <a-option v-for="item of currencyList" :label="item.label" :value="item.value"></a-option>
          </a-select>
        </div>

        <a-table style="margin-top: 10px" size="mini" class="table-two-line" :data="productList" :pagination="false">
          <template #columns>
            <a-table-column title="序号" :width="40" #cell="{ record, rowIndex }">{{ rowIndex + 1 }} </a-table-column>
            <a-table-column title="图片" :width="60" #cell="{ record }">
              <ImgPopover :src="getMainUrl(record)">
                <template #con>
                  <a-image width="60" height="60" fit="contain" :src="getMainUrl(record)" />
                </template>
              </ImgPopover>
            </a-table-column>
            <a-table-column title="MSKU/ASIN" :width="140" #cell="{ record }">
              <TextLimit position="top" :rows="1">{{ record.msku }}</TextLimit>
              <TextLimit position="top" :rows="1">{{ record.asin ? record.asin : '--' }}</TextLimit>
            </a-table-column>
            <a-table-column title="SKU" :width="140" #cell="{ record }">
              <TextLimit position="top" :rows="2">{{ $extract(record, 'product.sku') }}</TextLimit>
            </a-table-column>
            <a-table-column title="订购数量" :width="140" #cell="{ record, rowIndex }">
              <a-input @input="getAmtActual($event, record)" v-model="record.qtyOrdered" style="width: 100px" class="fl"></a-input>
              <icon-arrow-fall @click="setValue('qtyOrdered', record)" v-if="rowIndex == 0" class="arrow-icon fl" />
            </a-table-column>
            <a-table-column title="销售单价" :width="140" #cell="{ record, rowIndex }">
              <a-input @input="getAmtActual($event, record)" v-model="record.amtUnitSell" style="width: 100px" class="fl"></a-input>
              <icon-arrow-fall @click="setValue('amtUnitSell', record)" v-if="rowIndex == 0" class="arrow-icon fl" />
            </a-table-column>
            <a-table-column title="销售金额" :width="80" #cell="{ record }"> {{ (record.amtUnitSell * record.qtyOrdered).toFixed(2) }} </a-table-column>
            <a-table-column title="实付金额" :width="140" #cell="{ record, rowIndex }">
              <a-input v-model="record.amtActual" style="width: 100px" class="fl"></a-input>
              <icon-arrow-fall @click="setValue('amtActual', record)" v-if="rowIndex == 0" class="arrow-icon fl" />
            </a-table-column>
            <a-table-column title="优惠金额" :width="80" #cell="{ record }">{{ getAmtDiscount(record) }} </a-table-column>
            <a-table-column title="销售员" :width="140" #cell="{ record, rowIndex }">
              <a-select v-model="record.saler.id" class="fl" placeholder="请选择" style="width: 100px" allow-search allow-clear>
                <a-option v-for="item of userList" :label="item.userName" :value="item.id"></a-option>
              </a-select>
              <icon-arrow-fall @click="setSalerUser(record)" v-if="rowIndex == 0" class="arrow-icon fl" />
            </a-table-column>
            <a-table-column title="操作" :width="60" #cell="{ record, rowIndex }">
              <a-button type="text" @click="delProductItem(record, rowIndex)">移除</a-button>
            </a-table-column>
          </template>
        </a-table>
      </a-scrollbar>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>

  <AddProduct ref="addProduct" :sellerMarketId="form.sellerMarketId" @save="saveProduct" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam, listExpressProvider, pageExpressChannel } from '@/api/warehouse'
  import { saveOrUpdateOrderRelated, getOrderDetail } from '@/api/order'
  import { getShopMarketAll } from '@/api/base'
  import { currencySymbol } from '@/utils/globalData'
  import { getOrganizesUser, findShopMarketByParam } from '@/api/system'
  import { countriesOptions } from '@/utils/countries'
  import { Message } from '@arco-design/web-vue'
  import AddProduct from './addProduct.vue'
  import { set } from 'nprogress'
  import { dataTool } from 'echarts/core'
  export default defineComponent({
    props: ['type', 'id'],
    components: {
      AddProduct,
    },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const addProduct = ref()
      const data: any = reactive({
        form: {
          platform: 'amazon',
        },
        rules: {
          platform: [{ required: true, message: '请选择平台' }],
          platformOrderNumber: [{ required: true, message: '请输入平台订单号' }],
          marketplaceId: [{ required: true, message: '请选择站点' }],
          sellerMarketId: [{ required: true, message: '请选择店铺' }],
          buyerName: [{ required: true, message: '请输入买家姓名' }],
          gmtPurchase: [{ required: true, message: '请选择订购时间' }],
          gmtLatestShip: [{ required: true, message: '请选择承诺发货时间' }],
          userName: [{ required: true, message: '请输入收货人名字' }],
          phoneNumber: [{ required: true, message: '请输入收货人手机号' }],
          country: [{ required: true, message: '请选择国家' }],
          stateOrRegion: [{ required: true, message: '请输入省/州' }],
          stateOrRegionCode: [{ required: true, message: '请输入省/州代码' }],
          city: [{ required: true, message: '请输入城市名称' }],
          postalCode: [{ required: true, message: '请输入邮编' }],
          address: [{ required: true, message: '请输入地址' }],
        },
        loading: false,
        houseList: [],
        marketList: [],
        expressList: [],
        channelList: [],
        currencyList: [],
        productList: [],
        userList: [],
        userShopList: [],
        countriesOptions: countriesOptions,
        delItemIdList: [],
      })

      const skuNum = computed(() => {
        console.log(data.productList)
        let skuList: any = []
        data.productList.forEach((e: any) => {
          let index = skuList.findIndex((el: any) => el == e?.product?.sku || '')
          if (index == -1) {
            skuList.push(e?.product?.sku)
          }
        })
        return skuList.length
      })

      const title = computed(() => {
        return props.type == 'add' ? '手工录入订单' : '编辑订单'
      })
      const open = () => {
        data.delItemIdList = []
        getWareHouseList()
        getExpressList()
        getUserList()
        getUserShopList()
        for (const key in currencySymbol) {
          let obj = {
            value: key,
            label: currencySymbol[key],
          }
          data.currencyList.push(obj)
        }
        props.type == 'edit' ? getDetail() : ''
      }

      const getDetail = async () => {
        const res: any = await getOrderDetail({ id: props.id })
        let info: any = res?.data || {}
        data.form.platform = info.platform
        data.form.sellerId = info.sellerId
        data.form.shopName = info.shopName
        data.form.marketplaceId = info.marketplaceId
        data.form.platformOrderNumber = info.platformOrderNumber
        data.form.sellerMarketId = info.sellerMarketId
        data.form.buyerEmail = info.buyerEmail
        data.form.buyerName = info.buyerName
        data.form.buyerLeaveMessage = info.buyerLeaveMessage
        data.form.gmtPurchase = info.gmtPurchase
        data.form.gmtLatestShip = info.gmtLatestShip
        data.form.userName = info?.address?.userName || ''
        data.form.phoneNumber = info?.address?.phoneNumber || ''
        data.form.country = info?.address?.country || ''
        data.form.stateOrRegion = info?.address?.stateOrRegion || ''
        data.form.stateOrRegionCode = info?.address?.stateOrRegionCode || ''
        data.form.city = info?.address?.city || ''
        data.form.countryCode = info?.address?.countryCode || ''
        data.form.postalCode = info?.address?.postalCode || ''
        data.form.address = info?.address?.address || ''
        data.form.address1 = info?.address?.address1 || ''
        data.form.address2 = info?.address?.address2 || ''
        data.form.warehouseCode = info?.packageList[0]?.warehouseCode || ''
        data.form.warehouseName = info?.packageList[0]?.warehouseName || ''
        data.form.expressId = info?.packageList[0]?.expressId || ''
        data.form.expressName = info?.packageList[0]?.expressName || ''
        data.form.expressProviderCode = info?.packageList[0]?.expressProviderCode || ''
        data.form.expressProviderName = info?.packageList[0]?.expressProviderName || ''
        data.form.expressChannelCode = info?.packageList[0]?.shippingMethodCode || ''
        data.form.shippingMethodName = info?.packageList[0]?.shippingMethodName || ''
        data.form.firstPackageId = info?.packageList[0]?.id || ''
        data.form.firstAddressId = info?.address?.id || ''
        data.form.id = info.id
        data.form.currency = info.currency

        if (info.remarkList && info.remarkList[0]) {
          data.form.remark = info.remarkList[0].remark
        }

        data.productList = info.itemList.map((e: any) => {
          e.saler = {
            id: e.salerId,
            name: e.salerName,
          }

          e.product = {
            sku: e.productSku,
            id: e.productId,
          }

          e.amtUnitSell = e.amtSell / e.qtyOrdered

          return e
        })
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            if (data.productList.length <= 0) {
              return Message.error('请选择商品')
            }

            let params: any = {
              id: props.type == 'edit' ? data.form.id : '',
              sellerId: data.form.sellerId,
              shopName: data.form.shopName,
              marketplaceId: data.form.marketplaceId,
              sellerMarketId: data.form.sellerMarketId,
              platform: data.form.platform,
              source: 'OFFLINE',
              fulfillmentType: 'MFN',
              platformOrderNumber: data.form.platformOrderNumber,
              status: 201,
              buyerEmail: data.form.buyerEmail,
              buyerName: data.form.buyerName,
              buyerLeaveMessage: data.form.buyerLeaveMessage,
              currency: data.form.currency,
              gmtPurchase: data.form.gmtPurchase,
              gmtLatestShip: data.form.gmtLatestShip,
              itemList: [],
              remark: data.form.remark,
              address: {
                id: props.type == 'edit' ? data.form.firstAddressId : '',
                userName: data.form.userName,
                phoneNumber: data.form.phoneNumber,
                country: data.form.country,
                countryCode: data.form.countryCode,
                stateOrRegion: data.form.stateOrRegion,
                stateOrRegionCode: data.form.stateOrRegionCode,
                city: data.form.city,
                postalCode: data.form.postalCode,
                address: data.form.address,
                address1: data.form.address1,
                address2: data.form.address2,
              },
              packageList: [
                {
                  id: props.type == 'edit' ? data.form.firstPackageId : '',
                  platform: data.form.platform,
                  shippingLevel: 'Standard',
                  warehouseName: data.form.warehouseName,
                  warehouseCode: data.form.warehouseCode,
                  status: 'TO_CHECK',
                  expressId: data.form.expressId,
                  expressName: data.form.expressName,
                  expressProviderCode: data.form.expressProviderCode,
                  expressProviderName: data.form.expressProviderName,
                  shippingMethodCode: data.form.shippingMethodCode,
                  shippingMethodName: data.form.shippingMethodName,
                  fulfillmentType: 'MFN',
                },
              ],
            }
            data.productList.forEach((e: any) => {
              let obj = {
                id: props.type == 'edit' ? e.id : '',
                status: 201,
                asin: e.asin,
                msku: e.msku,
                fnsku: e.asin,
                productId: e?.product?.id || '',
                productName: e?.product?.skuName || '',
                productSku: e?.product?.sku || '',
                productPic: '',
                productCategoryId: e?.category?.id || '',
                productCategoryName: e?.category?.name || '',
                salerId: e?.saler?.id || '',
                salerName: e?.saler?.name || '',
                qtyOrdered: e.qtyOrdered,
                // qtyShipped: 2,
                amtSell: (e.amtUnitSell * e.qtyOrdered).toFixed(2),
                // amtUnitSell: 12.5,
                amtDiscount: getAmtDiscount(e),
                amtActual: e.amtActual,
                currency: data.form.currency,
                isCustom: false,
                platformItemId: props.type == 'edit' ? e.platformItemId : '',
              }
              params.itemList.push(obj)
            })

            if (props.type == 'edit') {
              params.delItemIdList = data.delItemIdList
            }

            try {
              data.loading = true
              const res: any = await saveOrUpdateOrderRelated(params)
              if (res) {
                props.type == 'add' ? Message.success('新增成功') : Message.success('编辑成功')
                emit('save')
                handleCancel()
              }
              data.loading = false
            } catch (error) {
              data.loading = false
            }
          }
        })
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res?.data
      }

      const getUserShopList = async () => {
        const res: any = await findShopMarketByParam()
        data.userShopList = res?.data || []
      }

      const changeCountry = (val: string) => {
        let obj: any = countriesOptions.find((e) => e.short == val)
        if (obj) {
          data.form.countryCode = obj.short
          data.form.country = obj.name
        } else {
          data.form.countryCode = ''
          data.form.country = ''
        }
      }

      const handleCancel = () => {
        data.form = {}
        data.productList = []
        formRef.value.resetFields()
        formRef.value.clearValidate()
        data.loading = false
        visible.value = false
      }

      const changeWarehouse = (code: string) => {
        let obj = data.houseList.find((e: any) => e.warehouseCode == code)
        if (code) {
          data.form.warehouseName = obj.warehouseName
        } else {
          data.form.warehouseName = ''
        }
      }

      const changeExpress = (code: string) => {
        let obj = data.expressList.find((e: any) => e.id == code)
        data.channelList = []
        if (code) {
          data.form.expressId = obj.id
          data.form.expressName = obj.expressName
          data.form.expressProviderCode = obj.providerCode
          data.form.expressProviderName = obj.providerName
          getExpressChannelList(obj.id)
        } else {
          data.form.expressId = ''
          data.form.expressName = ''
          data.form.expressProviderCode = ''
          data.form.expressProviderName = ''
        }
      }

      const getExpressChannelList = async (code: String) => {
        let params = {
          expressProviderId: code,
          enable: true,
          pageNum: 1,
          pageSize: 9999,
        }
        const res = await pageExpressChannel(params)
        data.channelList = res?.data?.records || []
      }

      const getExpressList = async () => {
        const res = await listExpressProvider({ scence: 'saleOrder' })
        data.expressList = res?.data || []
      }

      const getUserList = async () => {
        let params = {
          pageSize: 9999,
        }
        const res = await getOrganizesUser(params)
        data.userList = res?.data?.records
      }

      const saveProduct = (list: any) => {
        // data.productList = list
        list.forEach((e: any) => {
          let index = data.productList.findIndex((el: any) => e.id == el.id)
          if (index == -1) {
            data.productList.push(e)
          }
        })
      }

      const getMainUrl = (item: any) => {
        if (item.imageList && item.imageList[0]) {
          return item.imageList[0].link
        } else {
          return item.productPic
        }
      }

      const changeMarket = () => {}
      const changeShop = (id: string) => {
        let obj = data.userShopList.find((e: any) => e.sellerMarketId == id)
        data.form.sellerId = obj?.sellerId || ''
        data.form.shopName = obj.shopName
        data.form.marketplaceId = obj.marketplaceId
        data.form.sellerMarketId = obj?.sellerMarketId || ''
      }

      const getAmtActual = (info: any, item: any) => {
        item.amtActual = (item.qtyOrdered * item.amtUnitSell).toFixed(2)
      }

      const setValue = (key: string, item: any) => {
        data.productList.map((e: any) => {
          e[key] = item[key]
          e.amtActual = (e.qtyOrdered * e.amtUnitSell).toFixed(2)
          return e
        })
      }

      const setSalerUser = (item: any) => {
        data.productList.map((e: any) => {
          e.saler = item.saler
          return e
        })
      }

      const getChannelItem = (id: string) => {
        let obj = data.channelList.find((e: any) => e.code == id)
        if (obj) {
          data.form.shippingMethodCode = obj.code
          data.form.shippingMethodName = obj.name
        } else {
          data.form.shippingMethodCode = ''
          data.form.shippingMethodName = ''
        }
      }

      const getAmtDiscount = (record: any) => {
        let num1: any = (record.amtUnitSell * record.qtyOrdered).toFixed(2)
        return (num1 - record.amtActual).toFixed(2)
      }

      const delProductItem = (info: any, rowIndex: number) => {
        data.delItemIdList.push(info.id)
        data.productList.splice(rowIndex, 1)
        // console.log(data.delItemIdList)
      }

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        title,
        changeCountry,
        changeWarehouse,
        changeExpress,
        addProduct,
        saveProduct,
        getMainUrl,
        changeMarket,
        changeShop,
        getAmtActual,
        setValue,
        setSalerUser,
        getChannelItem,
        skuNum,
        getAmtDiscount,
        delProductItem,
      }
    },
  })
</script>

<style lang="less" scoped>
  .arrow-icon {
    font-size: 24px;
    margin-top: 3px;
  }
</style>
